/**
 * TodoList 应用主文件
 * 实现任务管理、本地存储、视图切换等核心功能
 */

class TodoApp {
    constructor() {
        // 应用配置常量
        this.STORAGE_KEY = 'todolist_data';
        this.TRASH_STORAGE_KEY = 'todolist_trash_data'; // 回收站数据存储键
        this.TASKS_PER_PAGE = 10;
        
        // 应用状态
        this.currentView = 'todo';
        this.currentPage = 1;
        this.currentTasks = [];
        this.trashedTasks = []; // 回收站任务数组
        this.selectedDate = null;
        this.currentMonth = new Date().getMonth();
        this.currentYear = new Date().getFullYear();
        this.editingTaskId = null;
        
        // 初始化存储系统
        this.storage = new IndexedDBStorage();
        this.dataMigration = new DataMigration(this.storage);
        this.storageReady = false;
        
        // 初始化应用
        this.init();
    }

    /**
     * 初始化应用
     */
    async init() {
        try {
            // 初始化 IndexedDB 存储
            await this.storage.initDB();
            
            // 等待存储系统完全准备就绪
            await this.storage.waitForReady();
            
            // 检查并执行数据迁移
            const needsMigration = await this.dataMigration.needsMigration();
            if (needsMigration) {
                console.log('检测到需要数据迁移，开始迁移...');
                const migrationResult = await this.dataMigration.migrate();
                
                if (migrationResult.success) {
                    console.log('数据迁移成功完成');
                    this.showMessage('数据已成功迁移到新的存储系统', 'success');
                } else {
                    console.error('数据迁移失败:', migrationResult.errors);
                    this.showMessage('数据迁移过程中出现问题，请检查控制台', 'error');
                }
            }
            
            this.storageReady = true;
            
            // 初始化应用组件
            this.bindEvents();
            await this.loadTasks();
            this.renderCurrentView();
            this.updateCalendar();
            
        } catch (error) {
            console.error('应用初始化失败:', error);
            this.showMessage('应用初始化失败，请刷新页面重试', 'error');
            
            // 降级到 localStorage（兼容性处理）
            this.storageReady = false;
            this.bindEvents();
            this.loadTasksFromLocalStorage();
            this.renderCurrentView();
            this.updateCalendar();
        }
    }

    /**
     * 绑定事件监听器
     */
    bindEvents() {
        // 导航菜单事件
        document.querySelectorAll('.nav-item').forEach(item => {
            item.addEventListener('click', (e) => {
                e.preventDefault();
                this.switchView(item.dataset.view);
            });
        });

        // 任务输入事件
        document.getElementById('add-task-btn').addEventListener('click', () => {
            this.addTask('todo');
        });
        
        document.getElementById('task-input').addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                this.addTask('todo');
            }
        });

        document.getElementById('today-add-btn').addEventListener('click', () => {
            this.addTask('today');
        });
        
        document.getElementById('today-task-input').addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                this.addTask('today');
            }
        });

        // 筛选事件
        document.getElementById('filter-btn').addEventListener('click', () => {
            this.filterTasks();
        });

        // 优先级筛选和排序事件（仅在元素存在时绑定）
        const priorityFilter = document.getElementById('priority-filter');
        if (priorityFilter) {
            priorityFilter.addEventListener('change', () => {
                this.filterTasks();
            });
        }
        
        const sortSelect = document.getElementById('sort-select');
        if (sortSelect) {
            sortSelect.addEventListener('change', () => {
                this.filterTasks();
            });
        }

        // 日历导航事件
        document.getElementById('prev-month').addEventListener('click', () => {
            this.navigateMonth(-1);
        });
        
        document.getElementById('next-month').addEventListener('click', () => {
            this.navigateMonth(1);
        });

        // 分页事件
        document.getElementById('prev-page').addEventListener('click', () => {
            this.changePage(-1);
        });
        
        document.getElementById('next-page').addEventListener('click', () => {
            this.changePage(1);
        });

        // 导出导入事件
        document.getElementById('export-btn').addEventListener('click', () => {
            this.exportReport();
        });
        
        document.getElementById('export-all-btn').addEventListener('click', () => {
            this.exportAllData();
        });
        
        document.getElementById('import-file-btn').addEventListener('click', () => {
            document.getElementById('import-file').click();
        });
        
        document.getElementById('import-file').addEventListener('change', async (e) => {
            await this.importData(e.target.files[0]);
        });
        
        document.getElementById('clear-all-btn').addEventListener('click', () => {
            this.clearAllData();
        });

        // 回收站事件（按钮可能不存在）
        const emptyTrashBtnInit = document.getElementById('empty-trash-btn');
        if (emptyTrashBtnInit) {
            emptyTrashBtnInit.addEventListener('click', async () => {
                await this.emptyTrash();
            });
        }

        // 模态框事件
        document.querySelector('.close').addEventListener('click', () => {
            this.closeModal();
        });
        
        document.getElementById('save-task-btn').addEventListener('click', async () => {
            await this.saveTaskFromModal();
        });
        
        document.getElementById('delete-task-btn').addEventListener('click', async () => {
            await this.deleteTaskFromModal();
        });
        
        document.getElementById('cancel-task-btn').addEventListener('click', () => {
            this.closeModal();
        });

        // 点击模态框外部关闭
        document.getElementById('task-modal').addEventListener('click', (e) => {
            if (e.target.id === 'task-modal') {
                this.closeModal();
            }
        });
    }

    /**
     * 生成唯一ID
     */
    generateId() {
        return Date.now().toString(36) + Math.random().toString(36).substr(2);
    }

    /**
     * 获取当前日期字符串
     */
    getCurrentDateString() {
        return new Date().toISOString().split('T')[0];
    }

    /**
     * 格式化日期显示
     */
    formatDate(dateString) {
        const date = new Date(dateString);
        return date.toLocaleDateString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit'
        });
    }

    /**
     * 获取日期范围
     */
    getDateRange(type) {
        const now = new Date();
        const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
        
        switch (type) {
            case 'today':
                return {
                    start: today,
                    end: new Date(today.getTime() + 24 * 60 * 60 * 1000 - 1)
                };
            case 'yesterday':
                const yesterday = new Date(today.getTime() - 24 * 60 * 60 * 1000);
                return {
                    start: yesterday,
                    end: new Date(yesterday.getTime() + 24 * 60 * 60 * 1000 - 1)
                };
            case 'week':
                const weekStart = new Date(today);
                weekStart.setDate(today.getDate() - today.getDay());
                const weekEnd = new Date(weekStart);
                weekEnd.setDate(weekStart.getDate() + 6);
                weekEnd.setHours(23, 59, 59, 999);
                return { start: weekStart, end: weekEnd };
            case 'month':
                const monthStart = new Date(today.getFullYear(), today.getMonth(), 1);
                const monthEnd = new Date(today.getFullYear(), today.getMonth() + 1, 0);
                monthEnd.setHours(23, 59, 59, 999);
                return { start: monthStart, end: monthEnd };
            case 'year':
                const yearStart = new Date(today.getFullYear(), 0, 1);
                const yearEnd = new Date(today.getFullYear(), 11, 31);
                yearEnd.setHours(23, 59, 59, 999);
                return { start: yearStart, end: yearEnd };
            default:
                return null;
        }
    }

    /**
     * 从本地存储加载任务（IndexedDB 版本）
     */
    async loadTasks() {
        if (!this.storageReady) {
            return this.loadTasksFromLocalStorage();
        }

        try {
            // 从 IndexedDB 加载主要任务数据
            const data = await this.storage.getItem(this.STORAGE_KEY);
            this.tasks = data ? data : [];
            
            // 确保旧任务数据兼容性，为没有progress属性的任务添加默认值
            this.tasks = this.tasks.map(task => ({
                ...task,
                progress: task.progress !== undefined ? task.progress : 0
            }));
            
            // 从 IndexedDB 加载回收站数据
            const trashData = await this.storage.getItem(this.TRASH_STORAGE_KEY);
            this.trashedTasks = trashData ? trashData : [];
            
            // 确保回收站任务也有progress属性
            this.trashedTasks = this.trashedTasks.map(task => ({
                ...task,
                progress: task.progress !== undefined ? task.progress : 0
            }));

            console.log(`从 IndexedDB 加载了 ${this.tasks.length} 个任务和 ${this.trashedTasks.length} 个回收站任务`);
            
        } catch (error) {
            console.error('从 IndexedDB 加载任务数据失败:', error);
            this.showMessage('加载任务数据失败，尝试从本地存储恢复', 'error');
            
            // 降级到 localStorage
            this.loadTasksFromLocalStorage();
        }
    }

    /**
     * 从 localStorage 加载任务（兼容性方法）
     */
    loadTasksFromLocalStorage() {
        try {
            const data = localStorage.getItem(this.STORAGE_KEY);
            this.tasks = data ? JSON.parse(data) : [];
            
            // 确保旧任务数据兼容性，为没有progress属性的任务添加默认值
            this.tasks = this.tasks.map(task => ({
                ...task,
                progress: task.progress !== undefined ? task.progress : 0
            }));
            
            // 加载回收站数据
            const trashData = localStorage.getItem(this.TRASH_STORAGE_KEY);
            this.trashedTasks = trashData ? JSON.parse(trashData) : [];
            
            // 确保回收站任务也有progress属性
            this.trashedTasks = this.trashedTasks.map(task => ({
                ...task,
                progress: task.progress !== undefined ? task.progress : 0
            }));

            console.log(`从 localStorage 加载了 ${this.tasks.length} 个任务和 ${this.trashedTasks.length} 个回收站任务`);
            
        } catch (error) {
            console.error('加载任务数据失败:', error);
            this.tasks = [];
            this.trashedTasks = [];
        }
    }

    /**
     * 保存任务到本地存储（IndexedDB 版本）
     */
    async saveTasks() {
        if (!this.storageReady) {
            return this.saveTasksToLocalStorage();
        }

        try {
            // 保存到 IndexedDB
            await this.storage.setItem(this.STORAGE_KEY, this.tasks);
            await this.storage.setItem(this.TRASH_STORAGE_KEY, this.trashedTasks);
            
            console.log(`已保存 ${this.tasks.length} 个任务和 ${this.trashedTasks.length} 个回收站任务到 IndexedDB`);
            
        } catch (error) {
            console.error('保存任务数据到 IndexedDB 失败:', error);
            this.showMessage('保存失败，尝试使用本地存储', 'error');
            
            // 降级到 localStorage
            this.saveTasksToLocalStorage();
        }
    }

    /**
     * 保存任务到 localStorage（兼容性方法）
     */
    saveTasksToLocalStorage() {
        try {
            localStorage.setItem(this.STORAGE_KEY, JSON.stringify(this.tasks));
            localStorage.setItem(this.TRASH_STORAGE_KEY, JSON.stringify(this.trashedTasks));
            
            console.log(`已保存 ${this.tasks.length} 个任务和 ${this.trashedTasks.length} 个回收站任务到 localStorage`);
            
        } catch (error) {
            console.error('保存任务数据失败:', error);
            this.showMessage('保存失败，请检查存储空间', 'error');
        }
    }

    /**
     * 添加新任务
     */
    async addTask(type) {
        const inputId = type === 'today' ? 'today-task-input' : 'task-input';
        const priorityId = type === 'today' ? 'today-priority-select' : 'priority-select';
        const input = document.getElementById(inputId);
        const prioritySelect = document.getElementById(priorityId);
        const content = input.value.trim();
        const priority = prioritySelect ? prioritySelect.value : 'medium';
        
        if (!content) {
            this.showMessage('请输入任务内容', 'error');
            return;
        }

        const task = {
            id: this.generateId(),
            content: content,
            completed: false,
            createdAt: new Date().toISOString(),
            scheduledDate: type === 'today' ? this.getCurrentDateString() : null,
            type: type,
            priority: priority, // 添加优先级字段
            progress: 0 // 默认进度为0%
        };

        this.tasks.push(task);
        await this.saveTasks();
        input.value = '';
        if (prioritySelect) {
            prioritySelect.value = 'medium'; // 重置优先级选择器
        }
        
        this.renderCurrentView();
        this.showMessage('任务添加成功', 'success');
    }

    /**
     * 切换任务完成状态
     */
    async toggleTask(taskId) {
        const task = this.tasks.find(t => t.id === taskId);
        if (task) {
            task.completed = !task.completed;
            task.completedAt = task.completed ? new Date().toISOString() : null;
            
            // 当任务被勾选为完成时，自动设置进度为100%
            if (task.completed) {
                task.progress = 100;
            }
            
            await this.saveTasks();
            this.renderCurrentView();
        }
    }

    /**
     * 编辑任务
     */
    editTask(taskId) {
        const task = this.tasks.find(t => t.id === taskId);
        if (task) {
            this.editingTaskId = taskId;
            document.getElementById('modal-task-content').value = task.content;
            document.getElementById('modal-task-priority').value = task.priority || 'medium';
            document.getElementById('modal-task-date').value = task.scheduledDate || '';
            document.getElementById('modal-task-status').value = task.completed ? 'completed' : 'pending';
            this.showModal();
        }
    }

    /**
     * 删除任务（移到回收站）
     */
    async deleteTask(taskId) {
        if (confirm('确定要删除这个任务吗？任务将被移到回收站。')) {
            // 找到要删除的任务
            const taskToDelete = this.tasks.find(t => t.id === taskId);
            if (taskToDelete) {
                // 添加删除时间戳
                taskToDelete.deletedAt = new Date().toISOString();
                
                // 移到回收站
                this.trashedTasks.push(taskToDelete);
                
                // 从原任务列表中移除
                this.tasks = this.tasks.filter(t => t.id !== taskId);
                
                await this.saveTasks();
                this.renderCurrentView();
                this.showMessage('任务已移到回收站', 'success');
            }
        }
    }

    /**
     * 转移任务到指定日期
     */
    moveTaskToDate(taskId, date) {
        const task = this.tasks.find(t => t.id === taskId);
        if (task) {
            task.scheduledDate = date;
            this.saveTasks();
            this.renderCurrentView();
            this.showMessage('任务转移成功', 'success');
        }
    }

    /**
     * 切换视图
     */
    switchView(viewName) {
        // 更新导航状态
        document.querySelectorAll('.nav-item').forEach(item => {
            item.classList.remove('active');
        });
        document.querySelector(`[data-view="${viewName}"]`).classList.add('active');

        // 隐藏所有视图
        document.querySelectorAll('.view-content').forEach(view => {
            view.classList.remove('active');
        });

        // 显示目标视图
        document.getElementById(`${viewName}-view`).classList.add('active');

        // 控制清空回收站按钮的显示/隐藏（按钮可能不存在）
        const emptyTrashBtn = document.getElementById('empty-trash-btn');
        if (emptyTrashBtn) {
            if (viewName === 'trash') {
                emptyTrashBtn.style.display = 'inline-flex';
            } else {
                emptyTrashBtn.style.display = 'none';
            }
        }

        // 更新标题
        const titles = {
            todo: '待办任务',
            today: '今天',
            yesterday: '昨天',
            week: '本周',
            month: '本月',
            year: '本年',
            all: '所有任务',
            trash: '回收站',
            calendar: '日历视图',
            settings: '设置'
        };
        document.getElementById('view-title').textContent = titles[viewName];

        this.currentView = viewName;
        this.currentPage = 1;
        this.renderCurrentView();
    }

    /**
     * 渲染当前视图
     */
    renderCurrentView() {
        // 隐藏分页控件（默认状态）
        const paginationContainer = document.querySelector('.pagination-container');
        paginationContainer.style.display = 'none';
        
        switch (this.currentView) {
            case 'todo':
                this.renderTodoTasks();
                paginationContainer.style.display = 'flex';
                this.updatePagination();
                break;
            case 'today':
                this.renderDateTasks('today');
                paginationContainer.style.display = 'flex';
                this.updatePagination();
                break;
            case 'yesterday':
                this.renderDateTasks('yesterday');
                paginationContainer.style.display = 'flex';
                this.updatePagination();
                break;
            case 'week':
                this.renderDateTasks('week');
                paginationContainer.style.display = 'flex';
                this.updatePagination();
                break;
            case 'month':
                this.renderDateTasks('month');
                paginationContainer.style.display = 'flex';
                this.updatePagination();
                break;
            case 'year':
                this.renderDateTasks('year');
                paginationContainer.style.display = 'flex';
                this.updatePagination();
                break;
            case 'all':
                this.renderAllTasks();
                paginationContainer.style.display = 'flex';
                this.updatePagination();
                break;
            case 'trash':
                this.renderTrashTasks();
                paginationContainer.style.display = 'flex';
                this.updatePagination();
                break;
            case 'calendar':
                this.updateCalendar();
                // 日历视图不需要分页
                break;
            case 'settings':
                // 设置页面不需要分页
                break;
        }
    }

    /**
     * 渲染待办任务
     */
    renderTodoTasks() {
        const todoTasks = this.tasks.filter(task => !task.scheduledDate);
        this.currentTasks = todoTasks;
        this.renderTaskList('todo-list', this.getPaginatedTasks(todoTasks));
    }

    /**
     * 渲染指定日期范围的任务
     */
    renderDateTasks(type) {
        const range = this.getDateRange(type);
        let filteredTasks = [];

        if (range) {
            filteredTasks = this.tasks.filter(task => {
                if (!task.scheduledDate) return false;
                const taskDate = new Date(task.scheduledDate);
                return taskDate >= range.start && taskDate <= range.end;
            });
        }

        this.currentTasks = filteredTasks;
        const listId = `${type}-list`;
        this.renderTaskList(listId, this.getPaginatedTasks(filteredTasks));
    }

    /**
     * 渲染所有任务
     */
    renderAllTasks() {
        this.currentTasks = this.tasks;
        this.renderTaskList('all-list', this.getPaginatedTasks(this.tasks));
    }

    /**
     * 渲染回收站任务
     */
    renderTrashTasks() {
        this.currentTasks = this.trashedTasks;
        this.renderTrashTaskList('trash-task-list', this.getPaginatedTasks(this.trashedTasks));
        
        // 更新回收站状态显示
        const emptyMessage = document.getElementById('trash-empty-message');
        const trashList = document.getElementById('trash-task-list');
        
        if (this.trashedTasks.length === 0) {
            emptyMessage.style.display = 'block';
            trashList.style.display = 'none';
        } else {
            emptyMessage.style.display = 'none';
            trashList.style.display = 'block';
        }
    }

    /**
     * 筛选任务
     */
    filterTasks() {
        const startDate = document.getElementById('start-date').value;
        const endDate = document.getElementById('end-date').value;
        const priorityFilter = document.getElementById('priority-filter').value;
        const sortBy = document.getElementById('sort-select').value;

        let filteredTasks = [...this.tasks];

        // 日期筛选
        if (startDate && endDate) {
            const start = new Date(startDate);
            const end = new Date(endDate);
            end.setHours(23, 59, 59, 999);

            filteredTasks = filteredTasks.filter(task => {
                if (!task.scheduledDate) return false;
                const taskDate = new Date(task.scheduledDate);
                return taskDate >= start && taskDate <= end;
            });
        }

        // 优先级筛选
        if (priorityFilter) {
            filteredTasks = filteredTasks.filter(task => 
                (task.priority || 'medium') === priorityFilter
            );
        }

        // 排序
        filteredTasks = this.sortTasks(filteredTasks, sortBy);

        this.currentTasks = filteredTasks;
        this.currentPage = 1;
        this.renderTaskList('all-list', this.getPaginatedTasks(filteredTasks));
        this.updatePagination();
    }

    /**
     * 排序任务
     */
    sortTasks(tasks, sortBy) {
        const sortedTasks = [...tasks];
        
        switch (sortBy) {
            case 'priority':
                const priorityOrder = { 'high': 3, 'medium': 2, 'low': 1 };
                return sortedTasks.sort((a, b) => {
                    const aPriority = priorityOrder[a.priority || 'medium'];
                    const bPriority = priorityOrder[b.priority || 'medium'];
                    return bPriority - aPriority; // 高优先级在前
                });
            
            case 'status':
                return sortedTasks.sort((a, b) => {
                    if (a.completed === b.completed) return 0;
                    return a.completed ? 1 : -1; // 未完成在前
                });
            
            case 'date':
            default:
                return sortedTasks.sort((a, b) => {
                    const aDate = new Date(a.scheduledDate || a.createdAt);
                    const bDate = new Date(b.scheduledDate || b.createdAt);
                    return bDate - aDate; // 最新日期在前
                });
        }
    }

    /**
     * 获取分页后的任务
     */
    getPaginatedTasks(tasks) {
        const startIndex = (this.currentPage - 1) * this.TASKS_PER_PAGE;
        const endIndex = startIndex + this.TASKS_PER_PAGE;
        return tasks.slice(startIndex, endIndex);
    }

    /**
     * 渲染任务列表
     */
    renderTaskList(listId, tasks) {
        const list = document.getElementById(listId);
        
        if (tasks.length === 0) {
            list.innerHTML = `
                <li class="empty-state">
                    <i class="fas fa-inbox"></i>
                    <h3>暂无任务</h3>
                    <p>添加一些任务来开始管理您的待办事项</p>
                </li>
            `;
            return;
        }

        list.innerHTML = tasks.map(task => `
            <li class="task-item" data-task-id="${task.id}">
                <div class="task-content">
                    <input type="checkbox" class="task-checkbox" 
                           ${task.completed ? 'checked' : ''} 
                           onchange="app.handleToggleTask('${task.id}')">
                    <span class="task-text ${task.completed ? 'completed' : ''}">${task.content}</span>
                    <span class="priority-badge priority-${task.priority || 'medium'}">${this.getPriorityText(task.priority || 'medium')}</span>
                    <span class="task-date">${task.scheduledDate ? `创建于 ${this.formatDate(task.scheduledDate)}` : `创建于 ${this.formatDate(task.createdAt)}`}</span>
                </div>
                <div class="task-progress">
                    <div class="progress-input-group">
                        <div class="progress-slider-container">
                            <input type="range" class="progress-slider" min="0" max="100" 
                                   value="${task.progress || 0}" 
                                   ${task.completed ? 'disabled' : ''}
                                   onchange="app.handleUpdateTaskProgress('${task.id}', this.value)"
                                   oninput="app.updateProgressSliderFill(this)">
                            <div class="progress-slider-fill" style="width: ${task.progress || 0}%"></div>
                        </div>
                        <span class="progress-value">${task.progress || 0}%</span>
                    </div>
                </div>
                <div class="task-actions">
                    <button class="btn btn-secondary" onclick="app.editTask('${task.id}')">
                        <i class="fas fa-edit"></i>
                    </button>
                    <button class="btn btn-danger" onclick="app.handleDeleteTask('${task.id}')">
                        <i class="fas fa-trash"></i>
                    </button>
                </div>
            </li>
        `).join('');
    }

    /**
     * 包装函数：异步删除任务（用于HTML onclick）
     */
    handleDeleteTask(taskId) {
        this.deleteTask(taskId).catch(error => {
            console.error('删除任务失败:', error);
            this.showMessage('删除任务失败', 'error');
        });
    }

    /**
     * 包装函数：异步恢复任务（用于HTML onclick）
     */
    handleRestoreTask(taskId) {
        this.restoreTask(taskId).catch(error => {
            console.error('恢复任务失败:', error);
            this.showMessage('恢复任务失败', 'error');
        });
    }

    /**
     * 包装函数：异步永久删除任务（用于HTML onclick）
     */
    handlePermanentDeleteTask(taskId) {
        this.permanentDeleteTask(taskId).catch(error => {
            console.error('永久删除任务失败:', error);
            this.showMessage('永久删除任务失败', 'error');
        });
    }

    /**
     * 包装函数：异步切换任务状态（用于HTML onclick）
     */
    handleToggleTask(taskId) {
        this.toggleTask(taskId).catch(error => {
            console.error('切换任务状态失败:', error);
            this.showMessage('操作失败', 'error');
        });
    }

    /**
     * 包装函数：异步更新任务进度（用于HTML oninput）
     */
    handleUpdateTaskProgress(taskId, progress) {
        this.updateTaskProgress(taskId, progress).catch(error => {
            console.error('更新任务进度失败:', error);
            this.showMessage('更新进度失败', 'error');
        });
    }

    /**
     * 更新任务进度
     */
    async updateTaskProgress(taskId, progress) {
        const task = this.tasks.find(t => t.id === taskId);
        if (task) {
            // 如果任务已完成，禁止修改进度
            if (task.completed) {
                return;
            }
            
            task.progress = parseInt(progress);
            
            // 如果进度达到100%，自动标记为完成
            if (task.progress === 100 && !task.completed) {
                task.completed = true;
                task.completedAt = new Date().toISOString();
            }
            // 如果进度小于100%且之前是完成状态，取消完成状态
            else if (task.progress < 100 && task.completed) {
                task.completed = false;
                task.completedAt = null;
            }
            
            await this.saveTasks();
            this.renderCurrentView();
        }
    }

    /**
     * 更新进度滑块填充效果
     */
    updateProgressSliderFill(slider) {
        const container = slider.parentElement;
        const fillElement = container.querySelector('.progress-slider-fill');
        const valueElement = container.parentElement.querySelector('.progress-value');
        
        if (fillElement) {
            fillElement.style.width = slider.value + '%';
        }
        if (valueElement) {
            valueElement.textContent = slider.value + '%';
        }
    }

    /**
     * 获取优先级文本
     */
    getPriorityText(priority) {
        const priorityMap = {
            'high': '高',
            'medium': '中',
            'low': '低'
        };
        return priorityMap[priority] || '中';
    }

    /**
     * 更新分页控件
     */
    updatePagination() {
        const totalPages = Math.ceil(this.currentTasks.length / this.TASKS_PER_PAGE);
        const prevBtn = document.getElementById('prev-page');
        const nextBtn = document.getElementById('next-page');
        const pageInfo = document.getElementById('page-info');

        prevBtn.disabled = this.currentPage <= 1;
        nextBtn.disabled = this.currentPage >= totalPages;
        pageInfo.textContent = `第 ${this.currentPage} 页，共 ${totalPages} 页`;
    }

    /**
     * 切换页面
     */
    changePage(direction) {
        const totalPages = Math.ceil(this.currentTasks.length / this.TASKS_PER_PAGE);
        const newPage = this.currentPage + direction;

        if (newPage >= 1 && newPage <= totalPages) {
            this.currentPage = newPage;
            this.renderCurrentView();
        }
    }

    /**
     * 更新日历
     */
    updateCalendar() {
        const calendarTitle = document.getElementById('calendar-title');
        const calendarGrid = document.getElementById('calendar-grid');
        
        calendarTitle.textContent = `${this.currentYear}年${this.currentMonth + 1}月`;

        // 生成日历网格
        const firstDay = new Date(this.currentYear, this.currentMonth, 1);
        const lastDay = new Date(this.currentYear, this.currentMonth + 1, 0);
        const startDate = new Date(firstDay);
        startDate.setDate(startDate.getDate() - firstDay.getDay());

        const days = [];
        const current = new Date(startDate);

        // 生成6周的日期
        for (let i = 0; i < 42; i++) {
            days.push(new Date(current));
            current.setDate(current.getDate() + 1);
        }

        calendarGrid.innerHTML = days.map(date => {
            const dateString = date.toISOString().split('T')[0];
            const tasksCount = this.getTasksForDate(dateString).length;
            const isCurrentMonth = date.getMonth() === this.currentMonth;
            const isToday = dateString === this.getCurrentDateString();
            const isSelected = dateString === this.selectedDate;

            return `
                <div class="calendar-day ${!isCurrentMonth ? 'other-month' : ''} 
                     ${isToday ? 'today' : ''} ${isSelected ? 'selected' : ''}"
                     onclick="app.selectDate('${dateString}')">
                    <div class="calendar-day-number">${date.getDate()}</div>
                    ${tasksCount > 0 ? `<div class="calendar-task-count">${tasksCount}</div>` : ''}
                </div>
            `;
        }).join('');
    }

    /**
     * 获取指定日期的任务
     */
    getTasksForDate(dateString) {
        return this.tasks.filter(task => task.scheduledDate === dateString);
    }

    /**
     * 选择日期
     */
    selectDate(dateString) {
        this.selectedDate = dateString;
        this.updateCalendar();
        
        const tasks = this.getTasksForDate(dateString);
        this.renderTaskList('calendar-task-list', tasks);
    }

    /**
     * 导航月份
     */
    navigateMonth(direction) {
        this.currentMonth += direction;
        
        if (this.currentMonth < 0) {
            this.currentMonth = 11;
            this.currentYear--;
        } else if (this.currentMonth > 11) {
            this.currentMonth = 0;
            this.currentYear++;
        }
        
        this.updateCalendar();
    }

    /**
     * 显示模态框
     */
    showModal() {
        document.getElementById('task-modal').style.display = 'block';
    }

    /**
     * 关闭模态框
     */
    closeModal() {
        document.getElementById('task-modal').style.display = 'none';
        this.editingTaskId = null;
    }

    /**
     * 从模态框保存任务
     */
    async saveTaskFromModal() {
        const content = document.getElementById('modal-task-content').value.trim();
        const priority = document.getElementById('modal-task-priority').value;
        const scheduledDate = document.getElementById('modal-task-date').value;
        
        if (!content) {
            this.showMessage('请输入任务内容', 'error');
            return;
        }

        if (this.editingTaskId) {
            // 编辑现有任务
            const task = this.tasks.find(t => t.id === this.editingTaskId);
            if (task) {
                task.content = content;
                task.priority = priority;
                task.scheduledDate = scheduledDate || null;
                task.updatedAt = new Date().toISOString();
            }
        } else {
            // 创建新任务
            const task = {
                id: this.generateId(),
                content: content,
                completed: false,
                createdAt: new Date().toISOString(),
                scheduledDate: scheduledDate || null,
                priority: priority,
                progress: 0
            };
            this.tasks.push(task);
        }

        await this.saveTasks();
        this.closeModal();
        this.renderCurrentView();
        this.showMessage(this.editingTaskId ? '任务更新成功' : '任务创建成功', 'success');
    }

    /**
     * 从模态框删除任务
     */
    async deleteTaskFromModal() {
        if (this.editingTaskId) {
            await this.deleteTask(this.editingTaskId);
            this.closeModal();
        }
    }

    /**
     * 导出当前视图报告
     */
    exportReport() {
        const viewTitles = {
            todo: '待办任务',
            today: '今天任务',
            yesterday: '昨天任务',
            week: '本周任务',
            month: '本月任务',
            year: '本年任务',
            all: '所有任务'
        };

        const title = viewTitles[this.currentView] || '任务报告';
        const tasks = this.currentTasks;
        
        this.generateReport(tasks, title);
    }

    /**
     * 生成报告
     */
    generateReport(tasks, title) {
        const completedTasks = tasks.filter(t => t.completed);
        const pendingTasks = tasks.filter(t => !t.completed);
        
        // 计算平均进度
        const totalProgress = tasks.reduce((sum, task) => sum + (task.progress || 0), 0);
        const averageProgress = tasks.length > 0 ? Math.round(totalProgress / tasks.length) : 0;
        
        // 按进度分组统计
        const progressStats = {
            notStarted: tasks.filter(t => (t.progress || 0) === 0).length,
            inProgress: tasks.filter(t => (t.progress || 0) > 0 && (t.progress || 0) < 100 && !t.completed).length,
            completed: completedTasks.length
        };
        
        const reportContent = `
${title}
生成时间: ${new Date().toLocaleString('zh-CN')}

=== 统计信息 ===
总任务数: ${tasks.length}
已完成: ${completedTasks.length}
待完成: ${pendingTasks.length}
完成率: ${tasks.length > 0 ? Math.round(completedTasks.length / tasks.length * 100) : 0}%
平均进度: ${averageProgress}%

=== 进度分布 ===
未开始 (0%): ${progressStats.notStarted}个
进行中 (1-99%): ${progressStats.inProgress}个
已完成 (100%): ${progressStats.completed}个

=== 已完成任务 ===
${completedTasks.map((task, index) => 
    `${index + 1}. ${task.content}${task.scheduledDate ? ` (${this.formatDate(task.scheduledDate)})` : ''} - 进度: ${task.progress || 0}%`
).join('\n') || '无'}

=== 待完成任务 ===
${pendingTasks.map((task, index) => 
    `${index + 1}. ${task.content}${task.scheduledDate ? ` (${this.formatDate(task.scheduledDate)})` : ''} - 进度: ${task.progress || 0}%`
).join('\n') || '无'}
        `.trim();

        this.downloadFile(reportContent, `${title}_${new Date().toISOString().split('T')[0]}.txt`);
        this.showMessage('报告导出成功', 'success');
    }

    /**
     * 导出所有数据
     */
    exportAllData() {
        const data = {
            exportTime: new Date().toISOString(),
            version: '1.0',
            tasks: this.tasks
        };

        const jsonContent = JSON.stringify(data, null, 2);
        this.downloadFile(jsonContent, `todolist_backup_${new Date().toISOString().split('T')[0]}.json`);
        this.showMessage('数据导出成功', 'success');
    }

    /**
     * 导入数据
     */
    async importData(file) {
        const reader = new FileReader();
        reader.onload = async (e) => {
            try {
                const data = JSON.parse(e.target.result);
                
                if (data.tasks && Array.isArray(data.tasks)) {
                    if (confirm('导入数据将覆盖现有数据，确定继续吗？')) {
                        this.tasks = data.tasks;
                        this.saveTasks();
                        this.renderCurrentView();
                        this.showMessage('数据导入成功', 'success');
                    }
                } else {
                    this.showMessage('无效的数据格式', 'error');
                }
            } catch (error) {
                console.error('导入数据失败:', error);
                this.showMessage('导入失败，请检查文件格式', 'error');
            }
        };
        
        reader.readAsText(file);
        // 清空文件输入
        document.getElementById('import-file').value = '';
    }

    /**
     * 清空所有数据
     */
    clearAllData() {
        if (confirm('确定要清空所有数据吗？此操作不可恢复！')) {
            // 清空任务列表
            this.tasks = [];
            // 清空回收站
            this.trashedTasks = [];
            this.saveTasks();
            this.renderCurrentView();
            this.showMessage('所有数据已清空（包括回收站）', 'success');
        }
    }

    /**
     * 下载文件
     */
    downloadFile(content, filename) {
        try {
            // 检测文件类型
            const isJson = filename.endsWith('.json');
            const mimeType = isJson ? 'application/json' : 'text/plain';
            
            // 创建Blob对象
            const blob = new Blob([content], { 
                type: `${mimeType};charset=utf-8` 
            });
            
            // 使用现代浏览器的下载API
            if (window.navigator && window.navigator.msSaveOrOpenBlob) {
                // IE浏览器支持
                window.navigator.msSaveOrOpenBlob(blob, filename);
            } else {
                // 现代浏览器支持
                const url = URL.createObjectURL(blob);
                const downloadLink = document.createElement('a');
                
                // 设置下载链接属性
                downloadLink.href = url;
                downloadLink.download = filename;
                downloadLink.style.display = 'none';
                
                // 添加到DOM并触发下载
                document.body.appendChild(downloadLink);
                downloadLink.click();
                
                // 清理资源
                setTimeout(() => {
                    document.body.removeChild(downloadLink);
                    URL.revokeObjectURL(url);
                }, 100);
            }
            
            // 显示成功消息
            this.showMessage(`文件 "${filename}" 下载成功`, 'success');
            
        } catch (error) {
            console.error('文件下载失败:', error);
            this.showMessage('文件下载失败，请重试', 'error');
        }
    }

    /**
     * 显示消息提示
     */
    showMessage(message, type = 'success') {
        // 移除现有消息
        const existingMessage = document.querySelector('.success-message, .error-message');
        if (existingMessage) {
            existingMessage.remove();
        }

        // 创建新消息
        const messageDiv = document.createElement('div');
        messageDiv.className = `${type}-message`;
        messageDiv.textContent = message;
        
        // 插入到工具栏后面
        const toolbar = document.querySelector('.toolbar');
        toolbar.parentNode.insertBefore(messageDiv, toolbar.nextSibling);

        // 3秒后自动移除
        setTimeout(() => {
            if (messageDiv.parentNode) {
                messageDiv.remove();
            }
        }, 3000);
    }

    /**
     * 渲染回收站任务列表
     */
    renderTrashTaskList(listId, tasks) {
        const list = document.getElementById(listId);
        
        if (tasks.length === 0) {
            list.innerHTML = `
                <li class="empty-state">
                    <i class="fas fa-trash"></i>
                    <h3>回收站为空</h3>
                    <p>已删除的任务将显示在这里</p>
                </li>
            `;
            return;
        }

        list.innerHTML = tasks.map(task => `
            <li class="task-item trash-task-item" data-task-id="${task.id}">
                <div class="task-content">
                    <span class="task-text">${task.content}</span>
                    <span class="priority-badge priority-${task.priority || 'medium'}">${this.getPriorityText(task.priority || 'medium')}</span>
                    <span class="task-date">${task.scheduledDate ? `创建于 ${this.formatDate(task.scheduledDate)}` : `创建于 ${this.formatDate(task.createdAt)}`}</span>
                    <span class="deleted-date">删除于: ${this.formatDate(task.deletedAt)}</span>
                </div>
                <div class="task-progress">
                    <div class="progress-bar-container">
                        <div class="progress-bar" style="width: ${task.progress || 0}%"></div>
                    </div>
                    <span class="progress-text">${task.progress || 0}%</span>
                </div>
                <div class="task-actions">
                    <button class="btn btn-success" onclick="app.handleRestoreTask('${task.id}')" title="恢复任务">
                        <i class="fas fa-undo"></i>
                    </button>
                    <button class="btn btn-danger" onclick="app.handlePermanentDeleteTask('${task.id}')" title="永久删除">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
            </li>
        `).join('');
    }

    /**
     * 恢复任务
     */
    async restoreTask(taskId) {
        const taskIndex = this.trashedTasks.findIndex(t => t.id === taskId);
        if (taskIndex !== -1) {
            const restoredTask = this.trashedTasks.splice(taskIndex, 1)[0];
            
            // 移除删除时间戳
            delete restoredTask.deletedAt;
            
            // 将任务恢复到主列表
            this.tasks.push(restoredTask);
            
            await this.saveTasks();
            this.renderCurrentView();
            this.showMessage('任务已恢复', 'success');
        }
    }

    /**
     * 永久删除任务
     */
    async permanentDeleteTask(taskId) {
        if (confirm('确定要永久删除这个任务吗？此操作无法撤销。')) {
            const taskIndex = this.trashedTasks.findIndex(t => t.id === taskId);
            if (taskIndex !== -1) {
                this.trashedTasks.splice(taskIndex, 1);
                await this.saveTasks();
                this.renderCurrentView();
                this.showMessage('任务已永久删除', 'success');
            }
        }
    }

    /**
     * 清空回收站
     */
    async emptyTrash() {
        if (confirm('确定要清空回收站吗？所有已删除的任务将被永久删除！')) {
            this.trashedTasks = [];
            await this.saveTasks();
            this.renderCurrentView();
            this.showMessage('回收站已清空', 'success');
        }
    }
}

// 初始化应用
const app = new TodoApp();